package model

import (
	"gitee.com/colzry/gin-postgres/utils/errmsg"
	"gorm.io/gorm"
	"golang.org/x/crypto/bcrypt"
)

type User struct {
	gorm.Model
	Username string `gorm:"type:varchar(20);not null " json:"username" validate:"required,min=4,max=12" label:"用户名"`
	Password string `gorm:"type:varchar(500);not null" json:"password" validate:"required,min=6,max=120" label:"密码"`
	Gender string `gorm:"type:varchar(2)" json:"gender" label:"性别"`
	Age string `gorm:"type:varchar(2)" json:"age" label:"年龄"`
}

func CheckUser(username string) (code int) {
	var user User
	db.Select("id").Where("username = ?", username).First(&user)
	if user.ID > 0 {
		return errmsg.ERROR_USERNAME_USED
	}
	return errmsg.SUCCESS
}

func CheckUserPwd(id int, loginPwd string) bool {
	var user User
	db.Where("id = ?", id).First(&user)
	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(loginPwd))
	return err == nil
}

func CreateUser(user *User) int {
	encyPwd, _ := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost) 
	user.Password = string(encyPwd)
	err := db.Create(&user).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

func GetUser(id int) (User, int) {
	var user User
	err := db.Where("ID = ?", id).First(&user).Error
	if err != nil {
		return user, errmsg.ERROR
	}
	return user, errmsg.SUCCESS
}

func GetUsers(pageSize, pageNum int) ([]User, int64) {
	var users []User
	var total int64

	db.Select("id,username,gender,age,created_at").Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&users)
	db.Model(&users).Count(&total)

	return users, total
}

func EditUser(data *User) int {
	var user User
	var maps = make(map[string]interface{})
	maps["username"] = data.Username
	maps["gender"] = data.Gender
	maps["age"] = data.Age
	err = db.Model(&user).Where("id = ? ", data.ID).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

func DeleteUser(id int) int {
	var user User
	err = db.Where("id = ? ", id).Delete(&user).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}